﻿using System;
using System.Collections.Generic;
using System.Linq;
using Journal.Common.Modules;
using Journal.Common.Objects.Enums;
using Journal.Domain.Models;
using Journal.Front.Presentation.Models.StudentModels;
using Journal.Front.Presentation.Models.UserModels;
using Tools.Security;
using Tools.Utilities;

namespace Journal.Front.Presentation.Mappers
{
    public static class UserMapper
    {
        public static void MapTo(this UserEditModel source, User user)
        {
            user.Email = user.Email;
            user.Login = source.Id == 0 ? StringUtils.CreateRandomString(5) : source.Login;
            CreatePassword(user);
            user.UserInfo.Gender = (GenderTypes)source.GenderId;
            user.UserInfo.Additionally = source.Additionally;
            user.UserInfo.DateBirth = source.DateBirth;
            user.UserInfo.Name = source.Name;
            user.UserInfo.Phone = source.Phone;
            user.UserInfo.Surname = source.Surname;
        }

        ////TODO
        public static void MapTo(this StudentEditModel source, User user)
        {
            user.Email = string.Empty;
            if (source.Id == 0)
            {
                user.Login = StringUtils.CreateRandomString(5);
            }

            CreatePassword(user);
            ////TODO
            user.UserInfo = new UserInfo { Gender = (GenderTypes) source.GenderId, Name = source.Name, Surname = source.Surname, DateBirth = DateTime.Now };
            user.Roles = new List<Role> { new Role() {Id = (int) Roles.Student } };
        }

        public static void MapTo(this StudentPartialEditModel source, User user)
        {
            user.Email = string.Empty;
            if (source.Id == 0)
            {
                user.Login = StringUtils.CreateRandomString(5);
            }

            CreatePassword(user);
            ////TODO
            user.UserInfo = new UserInfo { Gender = (GenderTypes)source.GenderId, Name = source.Name, Surname = source.Surname, DateBirth = DateTime.Now };
            user.Roles = new List<Role> { new Role() { Id = (int)Roles.Student } };
        }

        ////TODO
        private static void CreatePassword(User user)
        {
            user.PasswordSalt = Security.CreateSalt(128);
            user.Password = user.Id == 0 ? RijndaelAlgoritm.Encrypt(StringUtils.CreateRandomString(5), "a2N8zQIZUoAW2Xy7csfyI6McSu") : user.Password;
        }
    }
}